#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("TCP客户端");
    //连接主要的信号槽
    connect( &m_tcpsocket, SIGNAL(connected()) , this , SLOT(onConnected()));
    connect( &m_tcpsocket, SIGNAL(disconnected()) , this , SLOT(onDisconnected()));
    connect( &m_tcpsocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)) ,
             this , SLOT(onStateChanged(QAbstractSocket::SocketState)));
    connect( &m_tcpsocket, SIGNAL(error(QAbstractSocket::SocketError)) ,
             this , SLOT(onError(QAbstractSocket::SocketError)));

    //接收到数据时发出的信号
    connect( &m_tcpsocket, SIGNAL(readyRead()) ,
             this , SLOT(onReadyRead()));
}

Widget::~Widget()
{
    delete ui;
}

void   Widget::onConnected()
{
   ui->messageShoxEdit->appendPlainText("连接服务器成功！");
   ui->btnConnect->setText("断开");
   m_connected = true;
}

void   Widget::onDisconnected()
{
   ui->messageShoxEdit->appendPlainText("连接被断开！");
   ui->btnConnect->setText("连接");
   m_connected = false;
}
void   Widget::onStateChanged(QAbstractSocket::SocketState state)
{
    //枚举类型转为字符串、方便观测
     QString  strState = QMetaEnum::fromType
             <QAbstractSocket::SocketState>().valueToKey( state );

    QString str = QString("状态: %1").arg(strState);
    ui->messageShoxEdit->appendPlainText( str );
}

void   Widget::onError(QAbstractSocket::SocketError  err)
{
    //枚举类型转为字符串
     QString  strError = QMetaEnum::fromType
             <QAbstractSocket::SocketError>().valueToKey( err );
    QString str = QString("错误: %1").arg(strError);
    ui->messageShoxEdit->appendPlainText( str );
}


void Widget::onReadyRead()
{
   //有数据可以读
    QByteArray  data = m_tcpsocket.readAll();

    QString msg = data;
    QString str = QString("收到数据: %1").arg(msg);
    ui->messageShoxEdit->appendPlainText(str);
}

void Widget::on_btnConnect_clicked()
{
    if(!m_connected)
    {
        //获取IP与端口
        QString ip= ui->lineEditIP->text();
        uint  port = ui->lineEditPort->text().toUInt();
            //连接到TCP服务器
        m_tcpsocket.connectToHost(ip,port);
    }
    else
    {
        //断开与服务器的连接
        m_tcpsocket.disconnectFromHost();
    }
}

void Widget::on_btnSend_clicked()
{
    QString  msg = ui->messageEdit->text();
    //给服务端发送数据
    m_tcpsocket.write(msg.toUtf8());
}
